<?php
declare(strict_types=1);

namespace app\index\controller\api;

use Swoole\Coroutine;
use \Swoole\Http\Request;
use \Swoole\Http\Response;


class Store
{
    public \lib\User $user;
    public \lib\Merchant $merchant;

    public $middleware = [
        \lib\middleware\NetbarAuth::class=>[]
    ];

    # 读取网吧商品列表
    public function read(Request $request, Response $response)
    {
        $post = json_decode($request->getContent(), true);
        
        $db = new \sys\Db();
        $data = $db->table('tp_nb_goods_store')->where([['mid','=',$this->user->mid]])->order('sortid ASC')->select();
        return [
            'success'=>true,
            'data'=>$data
        ];
    }

    # 读取商品信息以及在货架或仓库中的数量
    public function goods(Request $request, Response $response)
    {
        $post = json_decode($request->getContent(), true);
        $validate = validate([
            'page' => 'require|number',
            'limit' => 'require|number',
            'cat_id' => 'number',
        ], __FILE__.'.'.__LINE__)->check($post);
        if(!$validate->pass()) return $validate->jsonSerialize();

        $db = new \sys\Db();
        $total = $data = $db->table('tp_nb_goods_rack,tp_nb_goods,tp_nb_goods_store_map')->where([['tp_nb_goods_rack.mid','=',$this->user->mid]])->count('id');
        $data = $db->table('tp_nb_goods_rack')->where([['tp_nb_goods_rack.mid','=',$this->user->mid]])
            ->join('tp_nb_goods_store_map', 'tp_nb_goods_store_map.goods_id = tp_nb_goods_rack.id','LEFT JOIN')
            ->join('tp_nb_goods', 'tp_nb_goods.id = tp_nb_goods_rack.goods_id','LEFT JOIN')
            ->field([
                'tp_nb_goods_rack.id',
                'tp_nb_goods_rack.goods_id',
                'tp_nb_goods_rack.category_ids',
                'tp_nb_goods_rack.sale_price',
                'tp_nb_goods_rack.allow_mb',        # 是否允许会员余额购买
                'tp_nb_goods_rack.prop',            # 0:计算库存 1:不计算库存 2:原材料
                'COALESCE(tp_nb_goods.on_sale, tp_nb_goods_store_map.on_sale) AS on_sale',   # 优先使用全局商品目录的上下架状态
                'COALESCE(tp_nb_goods_rack.name, tp_nb_goods.name) AS name',
                'COALESCE(tp_nb_goods_rack.img, tp_nb_goods.img) AS img',
                'COALESCE(tp_nb_goods_rack.code, tp_nb_goods.code) AS code',
                'COALESCE(tp_nb_goods_rack.spec, tp_nb_goods.spec, \'\') AS spec',
                'COALESCE(tp_nb_goods_store_map.store_num, 0) AS store_num',
                'tp_nb_goods.allow_ol',             # 是否允许线上购买
            ])->page($post['page'], $post['limit'])->select();
        return [
            'success'=>true,
            'data'=>[
                'total'=>$total,
                'data'=>$data
            ]
        ];
    }


    public function save(Request $request, Response $response){
        $post = json_decode($request->getContent(), true);
        $validate = validate([
            'id'    => 'uinteger',
            'name'  => 'require|length:1,64',
            'prop'  => 'require|uinteger|between:0,1',
        ], __FILE__.'.'.__LINE__)->check($post);
        if(!$validate->pass()) return $validate->jsonSerialize();
        $post['mid'] =  $mid = $this->merchant->id;
        $db = new \sys\Db();

        # Def 值不允许用户修改
        if(isset($post['def'])){unset($post['def']);}

        if(isset($post['id'])){
            if(null === ($store = \lib\data\Store::get((int)$post['id'])) || $store->mid != $mid){
                return ['success'=>false,'message'=>'修改失败'];
            }

            if($store->def){
                if((int)$post['prop'] != $store->prop)
                return ['success'=>false,'message'=>'默认货架允许修改类型.'];
            }

            if(null !== ($changed = $store->update(['name'=>$post['name'],'prop'=>$post['prop']]))){
                $db->table('tp_nb_goods_store')->where([['id','=',$post['id']],['mid','=',$this->user->mid]])->update($changed);
                $syncObject = new \lib\sync\Synchronize($mid);
                $syncObject->up('Store', $store->id, $changed);
                $this->merchant->push(['event'=>'sync', 'data'=>$syncObject->makeSyncData($db)]);
                return ['success'=>true,'message'=>'修改成功'];
            }
            return ['success'=>true,'message'=>'数据未作改变'];
        }else{
            $db->startTrans();
            try{
                $post['def'] = false;
                $post['createtime'] = time();
                $post['sortid'] = (int)$db->table('tp_nb_goods_store')->where([['mid','=',$this->user->mid]])->field('COALESCE(MAX(sortid), 0) + 1 AS `sortid`')->find()['sortid'];
                if(!$post['sortid']) $post['sortid'] = 1;
                if(null !== ($post['id'] = $db->table('tp_nb_goods_store')->insert($post))){
                    $db->commit();
                    $syncObject = new \lib\sync\Synchronize($mid);
                    $syncObject->put('Store', $post);
                    $this->merchant->push(['event'=>'sync', 'data'=>$syncObject->makeSyncData($db)]);
                    return ['success'=>true,'message'=>'添加成功'];
                }
                $db->rollback();
                return ['success'=>false,'message'=>'添加失败'];
            }catch(\Exception $e){
                $db->rollback();
                return ['success'=>false,'message'=>'添加失败'];
            }
            return ['success'=>false,'message'=>'添加失败'];
        }
    }

    /**
     * 删除仓库|货架
     */
    public function remove(Request $request, Response $response){
        $post = json_decode($request->getContent(), true);
        $validate = validate([
            'id'    => 'require|uinteger',
        ], __FILE__.'.'.__LINE__)->check($post);
        if(!$validate->pass()) return $validate->jsonSerialize();
        
        $mid = $this->merchant->id;
        $db = new \sys\Db();
        if(null === ($store = \lib\data\Store::get((int)$post['id'])) || $store->mid != $mid){
            return ['success'=>false,'message'=>'删除失败'];
        }

        if($store->def){
            return ['success'=>false,'message'=>'默认货架不能删除'];
        }

        if($store->getNumGoods() > 0){
            return ['success'=>false,'message'=>'仓库中还有商品，不能删除'];
        }
        $store->remove();

        $syncObject = new \lib\sync\Synchronize($mid);
        $goods = \lib\data\StoreComponents::getByStoreId($store->id);
        foreach($goods as $g){
            $g->remove();
            $syncObject->rm('StoreComponents', $g->id);
        }
        $syncObject->rm('Store', $store->id);
        $db->table('tp_nb_goods_store')->where([['id','=',$store->id]])->delete();
        $db->table('tp_nb_goods_store_map')->where([['store_id','=',$store->id]])->delete();
        $this->merchant->push(['event'=>'sync', 'data'=>$syncObject->makeSyncData($db)]);
        return ['success'=>true,'message'=>'删除成功']; 
    }
}